#include "head.h"

void userRegister(int net_fd, user_info *info, MYSQL *conn, pool_t *pool) {
    char sql_str[4096];
    memset(sql_str, 0, sizeof(sql_str));
    sprintf(sql_str, "%s%s", "select * from user where user_id = ", info->username);
    printf("sql_str = %s\n", sql_str);

    pthread_mutex_lock(&pool->sql_lock);
    int ret_mysql_query = mysql_query(conn, sql_str);
    printf("mysql_query return%d\n", ret_mysql_query);
    MYSQL_ERROR_CHECK(conn, ret_mysql_query, 1);

    MYSQL_RES *result;
    result = mysql_store_result(conn);

    MYSQL_ROW row;
    row = mysql_fetch_row(result);

    if(row == NULL) {
        //用户不存在
        mysql_free_result(result);
        pthread_mutex_unlock(&pool->sql_lock);
        
        train_t train;
        sprintf(info->command_str_return, "%s", getSalt(&train));
        info->flag = 0;
        //生成随机盐值发回客户端
        sendInfoStruct(net_fd, info);

        //接收密码哈希
        recvInfoStruct(net_fd, info);

        //新用户信息存入数据库
        memset(sql_str, 0, sizeof(sql_str));
        sprintf(sql_str, "insert into user values (%s, '%s', '%s', '%s')", info->username
                , "aaa", info->password, info->command_str_return);

        pthread_mutex_lock(&pool->sql_lock);
        int ret_mysql_query = mysql_query(conn, sql_str);
        printf("mysql_query return%d\n", ret_mysql_query);
        MYSQL_ERROR_CHECK(conn, ret_mysql_query, 1);

        memset(sql_str, 0, sizeof(sql_str));
        sprintf(sql_str, "insert into file_table (file_properties, father_id, flag, path, file_name, user_id) values (1, -1, 1, '/%s', '/%s', %s)"
                , info->username, info->username, info->username);
        ret_mysql_query = mysql_query(conn, sql_str);
        printf("mysql_query return%d\n", ret_mysql_query);
        MYSQL_ERROR_CHECK(conn, ret_mysql_query, 1);                                                                         

        pthread_mutex_unlock(&pool->sql_lock);
        //printf("%s\n", sql_str);
    }
    else {
        //用户已存在
        mysql_free_result(result);
        pthread_mutex_unlock(&pool->sql_lock);
        info->flag = -1;
        sendInfoStruct(net_fd, info);
    }
    return;
}
